package bean;

import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;

/*
 * 会话钝化，指将对象存储至硬盘；会话活化，指将对象从硬盘读取至内存
 * HttpSessionActivationListener负责监听被对话绑定的实现此接口的类的对象（即，会话通过setAttribute绑定的对象）
 * 以通知在该类对象的容器（会话）发生的活化或钝化事件
 * 此接口继承自java.util.EventListener接口，不需要在web.xml中配置
 * 要使此接口生效，须在META-INF/context.xml中配置会话钝化的最大空闲时间及会话钝化后的存储路径
 * HttpSessionBindingListener负责监听该类对象绑定到会话（即，会话通过setAttribute绑定的对象）后
 * 或正在从会话取消绑定的事件，此接口继承自java.util.EventListener接口，也不需要在web.xml中配置
 * Serializable负责序列化，是对话绑定的属性必须实现的接口
 */
public class CustomBean implements HttpSessionActivationListener, HttpSessionBindingListener, Serializable {
    private static final long serialVersionUID = -1564838884066105583L;
    private int attr1;
    private String attr2;

    public CustomBean() {
        super();
    }

    public CustomBean(int attr1, String attr2) {
        super();
        this.attr1 = attr1;
        this.attr2 = attr2;
    }

    public int getField1() { return attr1; }

    public void setField1(int field1) { this.attr1 = field1; }

    public String getField2() { return attr2; }

    public void setField2(String field2) { this.attr2 = field2; }

    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        HttpSessionActivationListener.super.sessionDidActivate(se);
        System.out.println("会话已被活化");
    }

    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        HttpSessionActivationListener.super.sessionWillPassivate(se);
        System.out.println("会话即将被钝化");
    }

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
        String className = this.getClass().getName();
        HttpSessionBindingListener.super.valueBound(event);
        System.out.println("会话绑定了属性名为" + attributeName + "类型为" + className + "的对象");
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        String attributeName = event.getName();
        String className = this.getClass().getName();
        HttpSessionBindingListener.super.valueUnbound(event);
        System.out.println("会话正在解除绑定属性名为" + attributeName + "类型为" + className + "的对象");
    }
}
